#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "los_sem.h"
#include "securec.h"



static UINT32 g_testTaskId01;
static UINT32 g_testTaskId02;

#define TASK_PRIO_TEST 5

static UINT32 g_semId;

void Example_SemTask1(void *argument)
{
    osStatus_t ret;
    printf("Example_SemTask1 try get sem g_semId ,timeout 10 ticks.\n");
    
    
    ret = osSemaphoreAcquire(g_semId, 10);
    
    if (ret == osOK) {
        osSemaphoreRelease(g_semId);
        return;
    }
    if (ret == osErrorTimeout) {
        printf("Example_SemTask1 timeout and try get sem g_semId wait forever.\n");
        
        ret = osSemaphoreAcquire(g_semId, osWaitForever);
        if (ret == osOK) {
            printf("Example_SemTask1 wait_forever and get sem g_semId .\n");
            osSemaphoreRelease(g_semId);
        }
    }
}

void Example_SemTask2(void *argument)
{
    osStatus_t ret;
    printf("Example_SemTask2 try get sem g_semId wait forever.\n");
    
    
    ret = osSemaphoreAcquire(g_semId, osWaitForever);
    
    if (ret == osOK) {
        printf("Example_SemTask2 get sem g_semId and then delay 20ticks .\n");
    }
    osDelay(20);  
    printf("Example_SemTask2 post sem g_semId .\n");
    osSemaphoreRelease(g_semId);
    
}

void ExampleTaskEntry(void)
{
    
    const osSemaphoreAttr_t sem_attr = {
        .name = "TestSem"
    };
    g_semId = osSemaphoreNew(1, 1, &sem_attr);
    
    
    const osThreadAttr_t task1_attr = {
        .name = "TestTsk1",
        .stack_size = 0x1000,
        .priority = osPriorityNormal1
    };
    const osThreadAttr_t task2_attr = {
        .name = "TestTsk2",
        .stack_size = 0x1000,
        .priority = osPriorityNormal2
    };
    
    
    g_testTaskId01 = osThreadNew(Example_SemTask1, NULL, &task1_attr);
    g_testTaskId02 = osThreadNew(Example_SemTask2, NULL, &task2_attr);
    
    
    osKernelStart();
    osDelay(40);  
    
    
    osSemaphoreDelete(g_semId);
    osThreadTerminate(g_testTaskId01);
    osThreadTerminate(g_testTaskId02);
}

APP_FEATURE_INIT(ExampleTaskEntry);